package org.acooly.secretbox.ui;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.acooly.android.utils.AndroidUtil;
import org.acooly.android.utils.DateUtils;
import org.acooly.android.utils.Page;
import org.acooly.android.utils.StringUtils;
import org.acooly.android.utils.ToastUtils;
import org.acooly.secretbox.Constants;
import org.acooly.secretbox.R;
import org.acooly.secretbox.common.BaseActivity;
import org.acooly.secretbox.service.AccountService;
import org.acooly.secretbox.service.AccountTypeService;
import org.acooly.secretbox.service.SettingService;
import org.acooly.secretbox.service.domain.Account;
import org.acooly.secretbox.service.domain.AccountType;
import org.acooly.secretbox.service.impl.AccountServiceImpl;
import org.acooly.secretbox.service.impl.AccountTypeServiceImpl;
import org.acooly.secretbox.service.impl.SettingServiceImpl;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import cn.domob.android.ads.DomobAdListener;
import cn.domob.android.ads.DomobAdView;

public class IndexActivity extends BaseActivity implements OnScrollListener {

	public static final String PUBLISHER_ID = "56OJz/YIuMwKJEJFMh";
	RelativeLayout mAdContainer;
	DomobAdView mAdview320x50;

	private AccountService accountService;
	private AccountTypeService accountTypeService;
	private SettingService settingService;

	private PopupWindow popupWindow;
	private ListView listView;
	private SimpleAdapter adapter;
	private List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
	/** 当前选中或正在操作的行数据 */
	private Map<String, Object> currentData;
	private Map<String, AccountType> accountTypes = new HashMap<String, AccountType>();

	/** 显示详情控件 */
	View showView = null;
	private int visibleLastIndex = 0;
	private int dataCount = 0;

	/** about */
	private PopupWindow pwAbout;
	private View viewAbout;

	private static final int PAGESIZE = 7;
	private static final int ACCOUNT_INTENT_REQUEST = 0;
	private static final List<String> CONTENT_MENU = new LinkedList<String>();
	static {
		CONTENT_MENU.add("管理");
		CONTENT_MENU.add("删除");
		CONTENT_MENU.add("发送");
	};

	private SimpleAdapter adapterTypes;
	private GridView gridView;
	private PopupWindow pwTypes;
	private View viewTypes;

	/** 查询条件 */
	private Map<String, String> conditions = new HashMap<String, String>();
	Button selectButton;

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			String status = bundle.getString("status");
			if (status.equals("0")) {
				adapter.notifyDataSetChanged();
				selectButton.setText(conditions.get("accountType"));
				if (pwTypes != null) {
					pwTypes.dismiss();
				}

			} else if (status.equals("1")) {
				showMessage("警告", bundle.getString("message"));
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index);
		accountService = new AccountServiceImpl(this);
		accountTypeService = new AccountTypeServiceImpl(this);
		settingService = new SettingServiceImpl(this);

		listView = (ListView) findViewById(R.id.account_list);
		listView.setOnScrollListener(this);
		adapter = new ListViewAdapter(this, data, R.layout.account_item1, new String[] {}, new int[] {});
		listView.setAdapter(adapter);

		registerForContextMenu(listView);
		listView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				AdapterContextMenuInfo ami = (AdapterContextMenuInfo) menuInfo;
				int position = ami.position;
				menu.setHeaderTitle((String) data.get(position).get("accountName"));
				for (int i = 0; i < CONTENT_MENU.size(); i++) {
					menu.add(0, i, 0, CONTENT_MENU.get(i));
				}
			}
		});

		// 点击事件
		// listView.setOnItemClickListener(new OnItemClickListener() {
		// @SuppressWarnings("unchecked")
		// @Override
		// public void onItemClick(AdapterView<?> parent, View view, int
		// position, long id) {
		// currentData = (Map<String, Object>) adapter.getItem(position);
		// openContextMenu(view);
		// }
		// });

		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@SuppressWarnings("unchecked")
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				currentData = (Map<String, Object>) adapter.getItem(position);
				return false;
			}
		});

		ImageView createButton = (ImageView) findViewById(R.id.ibtn_createAccount);
		createButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				editAccount(null);
			}
		});

		selectButton = (Button) findViewById(R.id.select_catalog);
		selectButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				showTypes();
			}
		});
		conditions.put("accountType", "全部");
		retrieve(0);

		showAd();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, "添加").setIcon(R.drawable.menu_addnew);
		menu.add(Menu.NONE, Menu.FIRST + 2, 2, "修改密码").setIcon(R.drawable.menu_settings);
		menu.add(Menu.NONE, Menu.FIRST + 3, 3, "设置分类").setIcon(R.drawable.menu_type);
		menu.add(Menu.NONE, Menu.FIRST + 4, 4, "关于").setIcon(R.drawable.menu_about);
		menu.add(Menu.NONE, Menu.FIRST + 5, 5, "退出").setIcon(R.drawable.menu_quit);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case Menu.FIRST + 1:
			editAccount(null);
			break;
		case Menu.FIRST + 2:
			Intent it = new Intent(IndexActivity.this, UserManageActivity.class);
			startActivity(it);
			break;
		case Menu.FIRST + 3:
			Intent intent = new Intent(IndexActivity.this, AccountTypeActivity.class);
			startActivity(intent);
			break;
		case Menu.FIRST + 4:
			showAbout();
			break;
		case Menu.FIRST + 5:
			exitDialog();
			break;
		}
		return false;
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		handleAction(item.getItemId());
		return super.onContextItemSelected(item);
	}

	/**
	 * 处理功能
	 * 
	 * @param action
	 */
	private void handleAction(int action) {

		switch (action) {
		case 0:
			// 管理，修改
			String accountId = String.valueOf(currentData.get("id"));
			editAccount(accountId);
			break;
		case 1:
			// 删除
			deleteAccount((Integer) currentData.get("id"));
			break;
		case 2:
			// 发送
			share();
			break;
		default:
			break;
		}
	}

	// 发送账户
	private void share() {
		Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
		String text = currentData.get("accountName") + "\n" + currentData.get("username") + "/" + currentData.get("password");
		intent.putExtra(Intent.EXTRA_TEXT, text);
		startActivity(Intent.createChooser(intent, getTitle()));
	}

	private void editAccount(String id) {
		Intent intent = new Intent(IndexActivity.this, AccountActivity.class);
		if (StringUtils.isNotBlank(id)) {
			intent.putExtra("id", id);
		}
		startActivityForResult(intent, ACCOUNT_INTENT_REQUEST);
	}

	private void deleteAccount(final int id) {
		try {
			AlertDialog.Builder builder = new Builder(IndexActivity.this);
			builder.setMessage("确定删除?");
			builder.setTitle("提示");
			builder.setPositiveButton("确认", new android.content.DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					accountService.delete(id);
					data.clear();
					retrieve(0);
					dialog.dismiss();
				}
			});
			builder.setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.create().show();
		} catch (Exception e) {
			ToastUtils.showShort(this, e.getMessage());
		}
	}

	private void retrieve(final int start) {
		final ProgressDialog progressDialog = ProgressDialog.show(IndexActivity.this, "", "正在加载...", true);
		new Thread() {
			@Override
			public void run() {
				Message message = new Message();
				Bundle bundle = new Bundle();
				try {
					Page<Account> page = accountService.retrieve(start, start + PAGESIZE, conditions);
					handleData(page);

					List<AccountType> types = accountTypeService.getAll();
					for (AccountType type : types) {
						accountTypes.put(type.getName(), type);
					}
					bundle.putString("status", "0");
				} catch (Exception e) {
					bundle.putString("status", "1");
					bundle.putString("message", e.getMessage());
				} finally {
					progressDialog.dismiss();
					message.setData(bundle);
					handler.sendMessage(message);
				}
			}
		}.start();

	}

	private void handleData(Page<Account> page) {
		this.dataCount = page.getTotal();
		if (page.getData() != null) {
			data.clear();
			for (Account account : page.getData()) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("id", account.getId());
				map.put("accountName", account.getAccountName());
				map.put("username", account.getUsername());
				map.put("password", account.getPassword());
				map.put("createTime", account.getCreateTime());
				map.put("accountType", account.getAccountType());
				map.put("comments", account.getComments());
				data.add(map);
			}
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
		Log.e("--------", firstVisibleItem + ";" + visibleItemCount + ";" + totalItemCount);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (visibleLastIndex == adapter.getCount() - 1 && adapter.getCount() < dataCount) {
			retrieve(visibleLastIndex);
		}
	}

	/**
	 * 显示Account
	 * 
	 * @param parent
	 */
	private void showAccount() {
		View parent = findViewById(R.id.ibtn_createAccount);
		if (popupWindow == null) {
			LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			showView = layoutInflater.inflate(R.layout.account_show, null);
			popupWindow = new PopupWindow(showView, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true);
			popupWindow.setAnimationStyle(android.R.style.Animation_Toast);
			popupWindow.setFocusable(true);
			ImageButton closeButton = (ImageButton) getView(showView, R.id.account_show_close);
			closeButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					popupWindow.dismiss();
				}
			});

			Button closeButtonButtom = (Button) getView(showView, R.id.account_show_cancel);
			closeButtonButtom.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					popupWindow.dismiss();
				}
			});

		}
		setTextView(showView, R.id.account_show_title, (String) currentData.get("accountName"));
		setTextView(showView, R.id.account_accountType_label, "类型:" + (String) currentData.get("accountType"));
		setTextView(showView, R.id.account_comments_label, "备注:" + (String) currentData.get("comments"));
		setTextView(showView, R.id.account_createTime_label, "时间:" + DateUtils.formart((Date) currentData.get("createTime")));
		setTextView(showView, R.id.account_password_label, "密码:" + (String) currentData.get("password"));
		setTextView(showView, R.id.account_username_label, "登录名:" + (String) currentData.get("username"));
		// 使其聚集
		popupWindow.setFocusable(true);
		// 设置允许在外点击消失
		popupWindow.setOutsideTouchable(true);
		// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);

	}

	/**
	 * 显示Account
	 * 
	 * @param parent
	 */
	private void showAbout() {
		View parent = findViewById(R.id.ibtn_createAccount);
		if (pwAbout == null) {
			LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			viewAbout = layoutInflater.inflate(R.layout.about, null);
			pwAbout = new PopupWindow(viewAbout, LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT, true);
			pwAbout.setAnimationStyle(android.R.style.Animation_Toast);
			pwAbout.setFocusable(true);
			// 设置允许在外点击消失
			pwAbout.setOutsideTouchable(true);
			// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
			pwAbout.setBackgroundDrawable(new BitmapDrawable());
			Button cancelButton = (Button) getView(viewAbout, R.id.account_show_cancel);
			cancelButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					pwAbout.dismiss();
				}
			});
		}
		pwAbout.showAtLocation(parent, Gravity.CENTER, 0, 0);
	}

	/**
	 * 询问是否退出
	 */
	private void exitDialog() {
		final AlertDialog dialog = new Builder(IndexActivity.this).create();
		dialog.show();
		final Window window = dialog.getWindow();
		window.setLayout(android.view.WindowManager.LayoutParams.FILL_PARENT, android.view.WindowManager.LayoutParams.WRAP_CONTENT);
		window.setContentView(R.layout.acooly_dialog);
		Button okButton = (Button) window.findViewById(R.id.acooly_dialog_ok);
		okButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				AndroidUtil.exitApp(IndexActivity.this);
			}
		});

		Button cancelButton = (Button) window.findViewById(R.id.acooly_dialog_cancel);
		cancelButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == ACCOUNT_INTENT_REQUEST) {
			if (resultCode == RESULT_OK) {
				this.data.clear();
				retrieve(0);
			}
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
				exitDialog();
				return true;
			}
		}
		return super.dispatchKeyEvent(event);
	}

	public class ListViewAdapter extends SimpleAdapter {
		private LayoutInflater mInflater;

		public ListViewAdapter(Context context, List<Map<String, Object>> data, int resource, String[] from, int[] to) {
			super(context, data, resource, from, to);
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int pos) {
			return data.get(pos);
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.account_item1, null);
				holder.icon = (ImageView) convertView.findViewById(R.id.list_item_img);
				holder.accountName = (TextView) convertView.findViewById(R.id.list_item_accountName);
				holder.username = (TextView) convertView.findViewById(R.id.list_item_username);
				holder.password = (TextView) convertView.findViewById(R.id.list_item_password);
				// holder.button = (Button)
				// convertView.findViewById(R.id.list_item_detail);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			AccountType type = accountTypes.get((String) data.get(position).get("accountType"));
			int iconResourceId = R.drawable.account_other;
			if (type != null) {
				iconResourceId = type.getIcon();
				type = null;
			}
			holder.icon.setImageBitmap(BitmapFactory.decodeResource(getResources(), iconResourceId));
			holder.accountName.setText((String) data.get(position).get("accountName"));
			holder.username.setText((String) data.get(position).get("username"));
			holder.password.setText((String) data.get(position).get("password"));
			return convertView;
		}
	}

	static class ViewHolder {
		public ImageView icon;
		public TextView accountName;
		public TextView username;
		public TextView password;
		public Button button;
	}

	private void showTypes() {

		View parent = findViewById(R.id.select_catalog);
		if (pwTypes == null) {
			LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			viewTypes = layoutInflater.inflate(R.layout.account_type_select, null);
			WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
			// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
			int screenWidth = windowManager.getDefaultDisplay().getWidth();
			Log.i("screenWidth", screenWidth + "");
			pwTypes = new PopupWindow(viewTypes, screenWidth - (parent.getLeft() * 2), LayoutParams.WRAP_CONTENT, true);
			// pwTypes.setAnimationStyle(android.R.style.Animation_Toast);
			// 设置允许在外点击消失
			pwTypes.setOutsideTouchable(true);
			// 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
			pwTypes.setBackgroundDrawable(new BitmapDrawable());
		}
		pwTypes.showAsDropDown(parent, 0, 15);

		if (adapterTypes == null) {
			List<String> types = StringUtils.toList(settingService.getValue(Constants.SETTING_ACCOUNT_TYPE), ",");
			List<Map<String, String>> typedatas = new ArrayList<Map<String, String>>(types.size());
			for (int i = 0; i < types.size(); i++) {
				Map<String, String> entry = new HashMap<String, String>();
				entry.put("name", types.get(i));
				typedatas.add(entry);
			}
			Map<String, String> entry = new HashMap<String, String>();
			entry.put("name", "全部");
			typedatas.add(entry);

			adapterTypes = new SimpleAdapter(this, typedatas, R.layout.account_type_item, new String[] { "name" }, new int[] { R.id.account_types_item_text });
			gridView = (GridView) getView(viewTypes, R.id.account_type_gride);
			gridView.setAdapter(adapterTypes);
			gridView.setOnItemClickListener(new OnItemClickListener() {

				@SuppressWarnings("unchecked")
				@Override
				public void onItemClick(AdapterView<?> adapter, View view, int position, long rowid) {
					Log.i("accountTypes:", adapter.getItemAtPosition(position).toString());
					Map<String, String> current = (Map<String, String>) adapter.getItemAtPosition(position);
					conditions.put("accountType", current.get("name"));
					retrieve(0);
				}

			});
		}
	}

	private void showAd() {
		mAdContainer = (RelativeLayout) findViewById(R.id.adcontainer);
		// 创建一个320x50的广告View
		mAdview320x50 = new DomobAdView(this, IndexActivity.PUBLISHER_ID, DomobAdView.INLINE_SIZE_320X50);

		// 设置广告view的监听器。
		mAdview320x50.setOnAdListener(new DomobAdListener() {
			@Override
			public void onReceivedFreshAd(DomobAdView adview) {
				Log.i("DomobSDKDemo", "onReceivedFreshAd");
				mAdContainer.setVisibility(View.VISIBLE);
			}

			@Override
			public void onFailedToReceiveFreshAd(DomobAdView adview) {
				Log.i("DomobSDKDemo", "onFailedToReceiveFreshAd");
			}

			@Override
			public void onLandingPageOpening() {
				Log.i("DomobSDKDemo", "onLandingPageOpening");
			}

			@Override
			public void onLandingPageClose() {
				Log.i("DomobSDKDemo", "onLandingPageClose");
			}
		});
		// 将广告View增加到视图中。
		mAdContainer.addView(mAdview320x50);
	}

}
